package com.sjr.easy.chat.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.sjr.easy.chat.model.OutboxMessage;
import com.sjr.easy.chat.service.OutboxMessageService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.sjr.easy.chat.repo.OutboxMessageRepo;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@Transactional
public class OutboxMessageServiceImpl implements OutboxMessageService {

    @Autowired
    private OutboxMessageRepo outboxMessageRepo;

    @Override
    public void addOutboxMessage(OutboxMessage outboxMessage) {
        log.info("outboxMessage:{}", JSON.toJSONString(outboxMessage));
        outboxMessageRepo.save(outboxMessage);
    }

    @Override
    public void batchAddOutboxMessage(List<OutboxMessage> outboxMessageList) {
        log.info("outboxMessageListSize:{}", CollectionUtils.size(outboxMessageList));
        if (CollectionUtils.isEmpty(outboxMessageList)) {
            return;
        }
        outboxMessageRepo.saveBatch(outboxMessageList, 1000);
    }

    @Override
    public List<OutboxMessage> getNewOutboxMessageList(Long targetUserId, Integer size) {
        log.info("userId:{}, size:{}", targetUserId, size);
        return outboxMessageRepo.getBaseMapper().getNewOutboxMessageList(targetUserId, size);
    }

    @Override
    public void batchACKOutboxMessage(Long targetUserId, List<Long> outboxMessageIdList) {
        log.info("targetUserId:{}, outboxMessageIdList:{}", targetUserId, JSON.toJSONString(outboxMessageIdList));
        if (CollectionUtils.isEmpty(outboxMessageIdList)) {
            log.warn("参数outboxMessageIdList为空");
            return;
        }
        Objects.requireNonNull(targetUserId, "接收消息用户ID不允许为空");
        LambdaQueryWrapper<OutboxMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OutboxMessage::getTargetUserId, targetUserId);
        queryWrapper.in(OutboxMessage::getId, outboxMessageIdList);
        queryWrapper.eq(OutboxMessage::getStatus, 0);
        List<OutboxMessage> outboxMessageList = outboxMessageRepo.list(queryWrapper);

        List<OutboxMessage> batchUpdateParams = Lists.newArrayList();
        for (OutboxMessage outboxMessage : outboxMessageList) {
            OutboxMessage item = new OutboxMessage();
            item.setId(outboxMessage.getId());
            item.setStatus(1);
            batchUpdateParams.add(item);
        }
        log.info("batchUpdateParams:{}", JSON.toJSONString(batchUpdateParams));
        outboxMessageRepo.updateBatchById(batchUpdateParams, 1000);
    }
}
